import React, {
    PureComponent
} from 'react'
import {
    View,
    Button,
    SafeAreaView,
    Text,
    StyleSheet,
    TextInput,
    ScrollView,
    Dimensions,
    TouchableOpacity
} from 'react-native'
import color from "../../../widget/color";
import MineCancelCell from '../../../widget/mine/MineCancelCell'
import MineShiXiaoCell from '../../../widget/mine/MineShiXiaoCell'
import MinePayCell from '../../../widget/mine/MinePayCell'
import MineUnPayCell from '../../../widget/mine/MineUnPayCell'
import MineRefuesCell from '../../../widget/mine/MineRefuesCell'
import MinePayOrderScene from "./MinePayOrderScene";
import MineUnPayDetailScene from "./MineUnPayDetailScene";
import api from '../../../api/api'
import method from '../../../api/method'
import {fetchGetRequest, fetchPostRequest} from '../../../api/NetworkTool'
import Tips from "react-native-root-tips";
import NetTool from "../../../api/NetTool";
import RefreshListView, {RefreshState} from "react-native-refresh-list-view";
import {NavigationActions} from "react-navigation";
import EmptyCouponView from "../../../widget/CommonEmptyView";
import CommonAlertDialog from '../../../widget/dialog/CommonAlertDialog'


const {width, height} = Dimensions.get('window')


type Props = {
    navigation: any,
}

type State = {
    data: Array < Object > ,
    refreshState: number,
}

export default class MineAllOrderScene extends PureComponent < Props, State > {
    static navigationOptions = ({
        navigation
    }: any) => ({
        headerTintColor: 'white',
        headerStyle: {
            backgroundColor: color.globalMainColor
        },
        title: '我的订单',
    });
    constructor(props) {
        super(props)
        this.state = {
            data: [],
            refreshState: RefreshState.Idle,
            show_alert:false,
            cancel_orderId:'',
            title:'',
            engish:'',
            type:'cancel',
            showShop:false,
            selectCourses:[],
        }
        this.page = 1
    }

    componentDidMount() {
        this.requestFirstPage()
    }
    requestData = async() =>{

        let params = {
            page:this.page,
        }

        let json = await NetTool.fetchGetRequest(api.getOrderList,method.get, params)


        let dataList = json.orders.map((info) => {
            return {
                course:info.course,
                payStatus: info.payStatus,
                payment: info.payment,
                price:info.price,
                orderSn:info.orderSn,
                id:info.id,
                refundStatus:info.refundStatus,
            }
        })

        return dataList
    }


    requestFirstPage = async() => {

        try {
            this.setState({refreshState: RefreshState.HeaderRefreshing})
            this.page = 1
            let dataList = await this.requestData()

            console.log('data',dataList)

            this.setState({
                data: dataList,
                refreshState: RefreshState.Idle,
            })
        } catch (error) {
            this.setState({
                refreshState: RefreshState.Failure,
            })
        }
    }
    requestNextPage = async() => {
        try {
            this.setState({refreshState: RefreshState.FooterRefreshing})
            this.page += 1
            let dataList = await this.requestData()

            console.log('requestNextPage',dataList)

            this.setState({
                data: [...this.state.data, ...dataList],
                refreshState: dataList.length <= 0 ? RefreshState.NoMoreData : RefreshState.Idle,
            })
            console.log('page',this.page)
        } catch (error) {
            this.setState({
                refreshState: RefreshState.Failure,
            })
        }
    }


    renderCell = ({item}: any) => {
        if (item.payStatus == "cancel" || item.payStatus == "expire") {
            return (
                <MineCancelCell
                    info={item} onPress={()=>{
                    this.props.navigation.navigate('MineCancelDetailScene',{orderId:item.id,callback:(data)=>{
                            this.requestFirstPage()
                        }})
                }} cancelPress={()=>{
                    this.deleteOrder(item.id)}} payPress={()=>{
                    this.props.navigation.navigate('MineCancelDetailScene',{orderId:item.id,callback:(data)=>{
                            this.requestFirstPage()
                        }})
                }}
                />
            )
        } else if (item.payStatus == "unpaid") {
            return (
                <MineUnPayCell
                  info={item}  onPress={()=>{this.onCellUnPaySelected(item)}} cancelPress={()=>{
                    this.cancelOrder(item.id)}} payPress={()=>{
                    this.props.navigation.navigate('MineUnPayDetailScene',{orderId:item.id,callback:(data)=>{
                            this.requestFirstPage()
                        }})
                }}
                />
            )
        } else if(item.payStatus == 'paid'){
            if (item.refundStatus == 'unrefund'){
                return (
                    <MinePayCell
                        coursePress={()=>{
                            //重置根视图，闪屏页=>主界面后销毁掉
                            const resetAction = NavigationActions.reset({
                                index: 0,
                                actions: [NavigationActions.navigate({ routeName: 'home'})]})
                            this.props.navigation.dispatch(resetAction)
                        }}
                        deletePress={()=>{
                            this.deleteOrder(item.id)
                        }} onPress={()=>{this.onCellPaySelected(item)}} info={item}
                    />
                )
            } else {
                return <MineRefuesCell
                    info={item}  onPress={()=>{this.onCellCancelSelected(item)}} payPress={()=>{
                    this.setState({showShop:true,selectCourses:item.course})
                }} cancelPress={()=>{
                    this.deleteOrder(item.id)
                }}/>
            }

        }
    }
    onCellCancelSelected(info){
        this.props.navigation.navigate('MineRefuesDetailScene',{orderId:info.id,callback:(data)=>{
                this.requestFirstPage()
            }})
    }
    deleteOrder(orderId){
        this.setState({show_alert:true,cancel_orderId:orderId,title:'确定删除订单？',engish:'确定',type:'delete'})


    }
    cancelOrder(orderId){
        this.setState({show_alert:true,cancel_orderId:orderId,title:'确定取消订单？',engish:'确定',type:'cancel'})

    }
    confirmOnpress(){
        if (this.state.type == 'cancel') {
            let params = {
                orderId:this.state.cancel_orderId,
            }
            fetchPostRequest(api.cancelOrder,method.post,params)
                .then(res=>{
                    this.requestFirstPage()
                })
                .catch(err=>{})
        }else if (this.state.type == 'delete'){
            let params = {
                orderId:this.state.cancel_orderId,
            }
            fetchPostRequest(api.removeOrder,method.post,params)
                .then(res=>{
                    this.requestFirstPage()
                })
                .catch(err=>{})
        }

    }
    keyExtractor = (item: Object, index: number) => {
        return index + ''
    }
    onCellSelected = (info: Object) => {
        // this.props.navigation.navigate('MineUnPayDetailScene')
    }
    onCellUnPaySelected(info){
        this.props.navigation.navigate('MineUnPayDetailScene',{orderId:info.id,callback:(data)=>{
                this.requestFirstPage()
            }})
    }
    onCellPaySelected(info) {
        this.props.navigation.navigate('MinePayDetailScene',{orderId:info.id})
    }
    join_shop(courseId1,courseId2){

        let params = {
            course:courseId1,
        }
        fetchGetRequest(api.join_shop,method.get,params)
            .then(res=>{
                if (courseId2){
                    this.join_shop1(courseId2)
                }else {
                    this.props.navigation.navigate('ShoppingCart')
                }
            })
            .catch(err=>{
                Tips.showFail(err,{mask:true})
            })
    }
    join_shop1(courseId){

        let params = {
            course:courseId,
        }
        fetchGetRequest(api.join_shop,method.get,params)
            .then(res=>{
            })
            .catch(err=>{
                Tips.showFail(err,{mask:true})
            })
    }
    render() {
        return (
            <View style={{flex:1}}>
                <RefreshListView
                    ListHeaderComponent={() => (
                        !this.state.data.length?
                            <EmptyCouponView height={(height-200)} tip={'您还没有订单'} source={require('../../../../res/img/order/dingdan.png')}/>
                            : null)
                    }
                    data={this.state.data}
                    renderItem={this.renderCell}
                    keyExtractor={this.keyExtractor}
                    refreshState={this.state.refreshState}
                    onHeaderRefresh={this.requestFirstPage}
                    onFooterRefresh={this.requestNextPage}
                />
                <CommonAlertDialog title={this.state.title} onPress={()=>{
                    this.confirmOnpress()
                }} closeModal={(statu)=>{        this.setState({show_alert:statu})}} confirmTitle={this.state.engish} show={this.state.show_alert}/>
                <CommonAlertDialog title={'订单已加入购物车'} onPress={()=>{
                    for (let i = 0; i < this.state.selectCourses.length; i+=2) {
                        let course1 = this.state.selectCourses[i]
                        if ((i+1) >= this.state.selectCourses.length){
                            this.join_shop(course1.id,null)
                        }else {
                            let course2 = this.state.selectCourses[i+1]
                            this.join_shop(course1.id,course2.id)
                        }

                    }
                }} closeModal={
                    (statu)=>{this.setState({showShop:statu})}
                } confirmTitle={'去订单支付'} show={this.state.showShop}/>
            </View>
        )
    }
}